<template>
    <view class="pay_page">
        <NavBar
            title="收银台"
            :isBack="true"
            fontColor="#312F2A"
            iconUrl="/ui-prod-2.8.0/back.png"
            :back="payCancelBackHandler"
            bgColor="#fffff" />
        <view class="amount_container">
            <view class="sub_title">需支付</view>
            <view>
                <text class="unit">￥</text>
                <text class="amount">{{ floatDivide(amount, 100).toFixed(2) }}</text>
            </view>
        </view>
        <view class="method_container">
            <view class="label">
                <img class="label_img" :src="getImgOssUrl('/ui-prod-2.16.0/wechat_pay.png')" />
                <text>微信支付</text>
            </view>
            <img class="img" :src="getImgOssUrl('/ui-prod-2.16.0/checked.png')" />
        </view>
        <view class="pay_btn" @click="payHandler"> 立即支付 </view>
    </view>
</template>

<script setup>
import router from '@/router';
import request from '@/request';
import { onShow, onUnload } from '@dcloudio/uni-app';
import { ref } from 'vue';
import store from '@/store';
import subscribe from '@/commons/subscribe';
import { getImgOssUrl, floatDivide } from '@/commons/utils';
import storage from '@/commons/storage';
import { debounce } from 'lodash';
import NavBar from '@/components/navBar';

const props = defineProps({
    appId: { type: String },
    // 来源页面：1-实物商品确认订单，2-虚拟商品下单，3-订单列表，4-订单详情
    type: { type: String || Number },
    orderId: { type: String },
    orderType: { type: String || Number },
    amount: { type: String || Number },
    orderSn: { type: String || Number },
    payMethod: { type: String || Number }
});

const envVersionList = {
    development: 'develop',
    test: 'trial',
    prod: 'release'
};

const jumpAPP = ref(false);
/**
 * 点击支付
 */
const payHandler = () => {
    if (jumpAPP.value) {
        return;
    }
    jumpAPP.value = true;
    const path = `pages/pay/index?amount=${props.amount}&orderSn=${props.orderSn}&payMethod=${
        props.payMethod
    }&ZW_TENANT_ID=${storage.get('ZW_TENANT_ID')}&ZW_CORP_ID=${storage.get('ZW_CORP_ID')}&ZW_SHOP_ID=${storage.get(
        'ZW_SHOP_ID'
    )}`;
    const payActionStore = store.payActionStore();
    payActionStore.orderSn = props.orderSn;
    uni.openEmbeddedMiniProgram({
        appId: props.appId,
        path: path,
        envVersion: envVersionList[store.useEnvStore().currentEnv],
        complete: () => {
            setTimeout(() => {
                jumpAPP.value = false;
            }, 1500);
        }
    });
};

/**
 * 检查支付结果
 */
const checkPayResultBack = () => {
    const payActionStore = store.payActionStore();
    const action = payActionStore.action;
    payActionStore.action = '';
    switch (action) {
        case 'pay_mp_cancel':
            payCancelHandler();
            break;
        case 'pay_mp_fail':
            uni.showToast({
                title: '订单支付异常，请刷新重试',
                icon: 'none',
                duration: 2000
            });
            setTimeout(() => {
                payFailHandler();
            }, 2000);
            break;
        case 'pay_mp_success':
            paySuccessHandler();
            break;
        default:
            break;
    }
};

/**
 * 支付成功
 */
const paySuccessHandler = () => {
    const type = Number(props.type);
    if ([1, 2, 3].includes(type)) {
        router.redirectTo({
            url: `/pages-cart/paystatus/index?orderId=${props.orderId}&orderType=${props.orderType}`
        });
    } else {
        router.back();
    }
};

/**
 * 支付失败
 */
const payFailHandler = () => {
    const type = Number(props.type);
    switch (type) {
        case 1:
            router.redirectTo({
                url: `/pages-cart/paystatus/index?orderId=${props.orderId}&type=2`
            });
            break;
        case 2:
            router.redirectTo({
                url: `/pages-cart/paystatus/index?orderId=${props.orderId}&type=2`
            });
            break;
        case 3:
            router.redirectTo({
                path: '/pages-user/orderdetail/index',
                query: {
                    orderId: props.orderId
                }
            });
            break;
        default:
            router.back();
            break;
    }
};

/**
 * 支付取消
 */
const payCancelHandler = () => {
    const type = Number(props.type);
    if ([1, 2].includes(type)) {
        uni.showModal({
            content: '是否放弃本次付款？',
            cancelText: '稍后付款',
            confirmText: '继续付款',
            confirmColor: '#FE292B',
            success: async res => {
                if (res.cancel) {
                    await subscribe('order_non_payment');
                    router.redirectTo({
                        url: `/pages-user/orderdetail/index?orderId=${props.orderId}`
                    });
                }
                if (res.confirm) {
                    payHandler();
                }
            }
        });
    } else if (type === 3) {
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${props.orderId}`
        });
    } else {
        router.back();
    }
};

/**
 * 点击左上角返回icon
 */
const payCancelBackHandler = () => {
    const type = Number(props.type);
    if ([1, 2].includes(type)) {
        uni.showModal({
            content: '是否放弃本次付款？',
            cancelText: '稍后付款',
            confirmText: '继续付款',
            confirmColor: '#FE292B',
            success: async res => {
                if (res.cancel) {
                    await subscribe('order_non_payment');
                    router.redirectTo({
                        url: `/pages-user/orderdetail/index?orderId=${props.orderId}`
                    });
                }
            }
        });
    } else {
        router.back();
    }
};

onShow(() => {
    if (props.orderSn) {
        checkPayResultBack();
    } else {
        uni.showToast({
            title: '页面参数错误，请重新进入小程序',
            icon: 'none',
            duration: 2000
        });
        setTimeout(() => {
            router.reLaunch({
                url: '/pages/tabbar/home'
            });
        }, 2000);
        return;
    }
});

onUnload(() => {
    // request('payCancelServ', { orderSn, payMethod });
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
